package javapop.framework.parser;

import javapop.framework.ParseContext;
import javapop.framework.ParseError;
import javapop.framework.ParseInput;
import javapop.framework.ParseResult;
import javapop.framework.Parser;

public class Literal extends Parser<String> {
	private String literal;
	private String description;
	
	public Literal(String literal) {
		if(literal==null)
			throw new IllegalArgumentException("Null literal");
		this.literal = literal;
		StringBuffer buf = new StringBuffer();
		buf.append("'");
		buf.append(literal);
		buf.append("'");
		description = buf.toString();
	}
	
	@Override
	public String getDescription() {
		return description;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public ParseResult<String> eval(ParseContext<?> ctx, ParseInput input) {
		if(input.consume(literal)) {
			ParseResult<String> result = buildResult(literal);			
			return result;
		} else {
			ParseResult<?> error = new ParseError("Expecting "+description);
			return (ParseResult<String>) error;
		}
	}
	
	@Override
	public boolean isMemoized() {
		return true;
	}
	
	@Override
	public int hashCode() {
		return literal.hashCode();
	}
	
	@Override
	public boolean equals(Object obj) {
		if(obj==null) return false;
		if(obj==this) return true;
		if(obj.getClass()!=this.getClass())
			return false;
		return ((Literal) obj).literal.equals(literal);
	}
	
}
